//GEN-FIRST:event_editProductButtonMouseClicked
/*//GEN-LAST:event_editProductButtonMouseClicked
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
 */
package supermarketgui;

//~--- non-JDK imports --------------------------------------------------------

import supermarketgui.utils.NumberCellRenderer;
import supermarketgui.utils.TableColumnAdjuster;

//~--- JDK imports ------------------------------------------------------------

import java.awt.event.*;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.NoResultException;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author JK
 */
public class ProductFrame extends javax.swing.JInternalFrame {
    private JMenuItem menuItemAdd;
    private JMenuItem menuItemEdit;
    private JMenuItem menuItemRemove;
    private Product   productSelected;
    DefaultTableModel model;
    DefaultRowSorter  sorter;

    // Variables declaration - do not modify
    private javax.swing.JPanel                     actionPanel;
    private javax.swing.JButton                    deleteProductButton;
    private javax.swing.JButton                    editProductButton;
    private javax.swing.JButton                    exitProductFrameButton;
    private javax.swing.JLabel                     filterLabel;
    private javax.swing.JTextField                 filterTextField;
    private javax.swing.JPanel                     jPanel1;
    private javax.swing.JButton                    newProductButton;
    private java.util.List<supermarketgui.Product> productList;
    private javax.persistence.EntityManager        productPUEntityManager;
    private javax.persistence.Query                productQuery;
    private javax.swing.JScrollPane                productScrollPane;
    private javax.swing.JTable                     productTable;
    private javax.swing.JPopupMenu                 tablePopupMenu;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;

    /**
     * Creates new form ProductFrame
     */
    public ProductFrame() {
        initComponents();
        productTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        TableColumnAdjuster tca = new TableColumnAdjuster(productTable);

        tca.adjustColumns();
        productTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
        tableAddPopupMenu();
        productTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    editRow();
                }
            }
        });

        // productTable.addMouseListener(new TableMouseListener(productTable));
        productTable.setComponentPopupMenu(tablePopupMenu);
        productTable.getColumnModel().getColumn(3).setCellRenderer(new NumberCellRenderer());

        // productTable.getRowSorter().setSortable(0,false);

        // λειτουργία ταξινόμησης πίνακα κάνοντας κλικ στη κεφαλίδα στήλης
        productTable.setAutoCreateRowSorter(true);
        sorter = ((DefaultRowSorter) productTable.getRowSorter());

        ArrayList list = new ArrayList();

        list.add(new RowSorter.SortKey(2, SortOrder.ASCENDING));
        sorter.setSortKeys(list);
        sorter.sort();
        filterTextField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent de) {
                newFilter();
            }
            @Override
            public void removeUpdate(DocumentEvent de) {
                newFilter();
            }
            @Override
            public void changedUpdate(DocumentEvent de) {
                newFilter();
            }
        });
    }

    private void newFilter() {
        String regex = filterTextField.getText().trim();

        if (regex.length() == 0) {
            sorter.setRowFilter(null);
        } else {
            List<RowFilter<Object, Object>> rfs = new ArrayList<>();

            rfs.add(RowFilter.regexFilter(regex, 0));
            rfs.add(RowFilter.regexFilter(regex, 1));
            rfs.add(RowFilter.regexFilter(regex, 2));
            rfs.add(RowFilter.regexFilter(regex, 3));
            rfs.add(RowFilter.regexFilter(regex, 4));

            RowFilter<Object, Object> af = RowFilter.orFilter(rfs);

            // sorter.setRowFilter(RowFilter.regexFilter("^" + text, 0));
            sorter.setRowFilter(af);
        }
    }

    private void tableAddPopupMenu() {
        menuItemAdd = new JMenuItem("Προσθήκη Νέου Προϊόντος");
        menuItemAdd.setMnemonic('\u03a0');
        menuItemAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/plus_orange.png")));
        menuItemEdit = new JMenuItem("Επεξεργασία Προϊόντος");
        menuItemEdit.setMnemonic('\u0395');
        menuItemEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/edit.png")));
        menuItemRemove = new JMenuItem("Διαγραφή Προϊόντος");
        menuItemRemove.setMnemonic('\u0394');
        menuItemRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/erase.png")));
        tablePopupMenu.add(menuItemAdd);
        tablePopupMenu.add(menuItemEdit);
        tablePopupMenu.add(new JSeparator());
        tablePopupMenu.add(menuItemRemove);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        bindingGroup           = new org.jdesktop.beansbinding.BindingGroup();
        productPUEntityManager = java.beans.Beans.isDesignTime()
                                 ? null
                                 : javax.persistence.Persistence.createEntityManagerFactory(
                                     "SuperMarketGUIPU").createEntityManager();
        tablePopupMenu         = new javax.swing.JPopupMenu();
        productQuery           = java.beans.Beans.isDesignTime()
                                 ? null
                                 : productPUEntityManager.createQuery("SELECT p FROM Product p");
        productList            = java.beans.Beans.isDesignTime()
                                 ? java.util.Collections.emptyList()
                                 : productQuery.getResultList();
        productScrollPane      = new javax.swing.JScrollPane();
        productTable           = new javax.swing.JTable();
        actionPanel            = new javax.swing.JPanel();
        newProductButton       = new javax.swing.JButton();
        editProductButton      = new javax.swing.JButton();
        deleteProductButton    = new javax.swing.JButton();
        exitProductFrameButton = new javax.swing.JButton();
        jPanel1                = new javax.swing.JPanel();
        filterLabel            = new javax.swing.JLabel();
        filterTextField        = new javax.swing.JTextField();
        tablePopupMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablePopupMenuMouseClicked(evt);
            }
        });
        setTitle("Διαχείριση Προϊόντων");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/basket.png")));    // NOI18N
        setMinimumSize(new java.awt.Dimension(468, 542));

        org.jdesktop.swingbinding.JTableBinding jTableBinding =
            org.jdesktop.swingbinding.SwingBindings.createJTableBinding(
                org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, productList, productTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding =
            jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${productId}"));

        columnBinding.setColumnName("ΚωδΠρ");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${code}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Προϊόν");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}"));
        columnBinding.setColumnName("Τιμή");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${points}"));
        columnBinding.setColumnName("Πόντοι");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        productTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                productTableMouseClicked(evt);
            }
        });
        productScrollPane.setViewportView(productTable);
        getContentPane().add(productScrollPane, java.awt.BorderLayout.CENTER);
        newProductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/plus_orange.png")));    // NOI18N
        newProductButton.setMnemonic('\u039d');
        newProductButton.setText("Νέο  ");
        newProductButton.setToolTipText("Δημιουργία νέου προϊόντος");
        newProductButton.setMaximumSize(new java.awt.Dimension(125, 25));
        newProductButton.setMinimumSize(new java.awt.Dimension(125, 25));
        newProductButton.setPreferredSize(new java.awt.Dimension(125, 25));
        actionPanel.add(newProductButton);
        editProductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/edit.png")));    // NOI18N
        editProductButton.setMnemonic('\u0395');
        editProductButton.setText("Επεξεργασία");
        editProductButton.setToolTipText("Επεξεργασία επιλεγμένου προϊόντος");
        editProductButton.setMaximumSize(new java.awt.Dimension(125, 25));
        editProductButton.setMinimumSize(new java.awt.Dimension(125, 25));
        editProductButton.setPreferredSize(new java.awt.Dimension(125, 25));
        editProductButton.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                editProductButtonMouseClicked(evt);
            }
        });
        editProductButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editProductButtonActionPerformed(evt);
            }
        });
        actionPanel.add(editProductButton);
        deleteProductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/erase.png")));    // NOI18N
        deleteProductButton.setMnemonic('\u0394');
        deleteProductButton.setText("Διαγραφή");
        deleteProductButton.setToolTipText("Διαγραφή προϊόντος");
        deleteProductButton.setMaximumSize(new java.awt.Dimension(125, 25));
        deleteProductButton.setMinimumSize(new java.awt.Dimension(125, 25));
        deleteProductButton.setPreferredSize(new java.awt.Dimension(125, 25));
        actionPanel.add(deleteProductButton);
        exitProductFrameButton.setIcon(
            new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/button_grey_close.png")));    // NOI18N
        exitProductFrameButton.setMnemonic('\u039a');
        exitProductFrameButton.setText("Κλείσιμο");
        exitProductFrameButton.setToolTipText("Κλείσιμο φόρμας προϊόντων");
        exitProductFrameButton.setMaximumSize(new java.awt.Dimension(125, 25));
        exitProductFrameButton.setMinimumSize(new java.awt.Dimension(125, 25));
        exitProductFrameButton.setPreferredSize(new java.awt.Dimension(125, 25));
        actionPanel.add(exitProductFrameButton);
        getContentPane().add(actionPanel, java.awt.BorderLayout.PAGE_END);
        filterLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarketgui/icons/filter.png")));    // NOI18N
        filterLabel.setText("Αναζήτηση:");
        jPanel1.add(filterLabel);
        filterTextField.setColumns(10);
        jPanel1.add(filterTextField);
        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);
        bindingGroup.bind();
        pack();
    }    // </editor-fold>

    private void tablePopupMenuMouseClicked(java.awt.event.MouseEvent evt) {

        // TODO add your handling code here:
        productTableMouseClicked(evt);
    }

    private void productTableMouseClicked(java.awt.event.MouseEvent evt) {

        // TODO add your handling code here:
    }

    private void editProductButtonMouseClicked(java.awt.event.MouseEvent evt) {

        // TODO add your handling code here:
        editRow();
    }

    private void editProductButtonActionPerformed(java.awt.event.ActionEvent evt) {

        // TODO add your handling code here:
    }

    /**
     *
     * @param event
     */
    public void actionPerformed(ActionEvent event) {
        JMenuItem menu = (JMenuItem) event.getSource();

        if (menu == menuItemAdd) {
            addNewRow();
        } else if (menu == menuItemRemove) {
            removeCurrentRow();
        } else if (menu == menuItemEdit) {
            editRow();
        }
    }

    private void addNewRow() {

        // tableModel.addRow(new String[0]);
    }

    private void removeCurrentRow() {
        if (this.purchaseProductId(-1) == null) {
            int selectedRow = productTable.getSelectedRow();

            model.removeRow(selectedRow);
        }
    }

    // θέλει αλαλγή

    /**
     *
     * @param productId
     * @return
     */
        public Product purchaseProductId(int productId) {
        try {
            return productPUEntityManager.createNamedQuery("Product.findByProductId",
                    Product.class).setParameter("ProductId", productId).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    private void editRow() {
        int row = this.productTable.getSelectedRow();

        productSelected = productList.get(this.productTable.convertRowIndexToModel(row));

        ProductEdit frame = new ProductEdit(null, true);

        frame.setTitle("Επεξεργασία Προϊόντος");
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setProduct(productSelected);
        frame.setVisible(true);

        if (frame.getFlagSave() == true) {
            if (!productPUEntityManager.getTransaction().isActive()) {
                productPUEntityManager.getTransaction().begin();
            }

            productSelected = frame.getProduct();
            productPUEntityManager.persist(productSelected);
            productPUEntityManager.getTransaction().commit();
            productList.set(row, productSelected);
            model = (DefaultTableModel) productTable.getModel();
            model.fireTableDataChanged();
        } else {
            JOptionPane.showMessageDialog(this, "Η επεξεργασία ακυρώθηκε", "Μήνυμα", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // End of variables declaration
}


//~ Formatted by Jindent --- http://www.jindent.com
